package com.simple.car.loader.server.annotation.impl;

import com.simple.car.loader.server.annotation.Function;
import com.simple.car.loader.server.manager.impl.BeamManager;
import com.simple.car.loader.server.tools.ReflectionsTool;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.Set;

public class FunctionImpl {

    public static void init() {
        Set<Class<?>> classes = ReflectionsTool.getClassByAnnotationClass(Function.class);
        if (classes == null || classes.isEmpty()) {
            return;
        }
        classes.forEach(aClass -> {
            try {
                Constructor<?> constructor = aClass.getConstructor();
                boolean accessible = constructor.isAccessible();
                try {
                    Function function = aClass.getDeclaredAnnotation(Function.class);
                    if (function == null){
                        return;
                    }
                    constructor.setAccessible(true);
                    Object instance = constructor.newInstance();

                    String value = function.value();
                    if (value.isEmpty()) {
                        value = aClass.getName();
                    }
                    BeamManager.getInstance().register(value, instance);
                } finally {
                    constructor.setAccessible(accessible);
                }
            } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException | InstantiationException e) {
                e.printStackTrace();
            }
        });
    }
}
